<template>
    <el-card shadow="never">
        <store-progress v-model="step" :type="2" />
    </el-card>
    <el-card shadow="never" style="margin: 16px 0">
        <div class="content">
            <div class="storeTips">
                <store-tips :type="7" />
            </div>
            <div class="line"></div>
            <div v-show="step === 1" class="msg">
                <div class="title">店铺基本信息</div>
                <el-form
                    ref="storeBaseFormRef"
                    :model="storeBaseForm"
                    :rules="storeBaseFormRules"
                    label-width="auto"
                    :disabled="type == 'look'">
                    <el-form-item v-if="type == 'edit' || type == 'look'" label="客易达店铺ID" prop="retail_shop_id">
                        <el-input v-model.trim="storeBaseForm.retail_shop_id" disabled />
                    </el-form-item>
                    <el-form-item label="店铺名称" prop="name">
                        <el-input v-model.trim="storeBaseForm.name" placeholder="请输入店铺名称" />
                    </el-form-item>
                    <el-form-item label="抖店ID" prop="external_shop_id">
                        <div class="withTips">
                            <el-input
                                v-model.trim="storeBaseForm.external_shop_id"
                                :disabled="route.query.shop_id"
                                placeholder="请输入抖店ID" />
                            <span @click="toCheck('doudian_view_shop_id')">如何查看抖店ID</span>
                        </div>
                    </el-form-item>
                    <el-form-item label="数据支持">
                        <el-radio-group v-model="storeBaseForm.data_support" :disabled="disabled">
                            <el-radio :label="1" size="small">支持手动上传</el-radio>
                        </el-radio-group>
                        <div class="formTips">无需店铺授权，用户通过抖店后台下载订单、商品数据，导入系统。</div>
                    </el-form-item>
                    <el-form-item label="" label-width="80px">
                        <el-checkbox
                            v-model="storeBaseForm.sync_type"
                            label="自动同步"
                            :true-label="1"
                            :false-label="2" />
                        <div class="formTips">
                            <span>
                                勾选该项后，同意签署
                                <span class="toAgreement" @click="toAgreement">《客易达数据安全隐私协议》</span>
                                的文件。客易达将自动同步来自抖店店铺的订单、商品数据。
                            </span>
                        </div>
                    </el-form-item>
                    <el-form-item v-if="storeBaseForm.sync_type === 1" label="同步版本">
                        <el-radio-group v-model="storeBaseForm.sync_version" @change="handleSync">
                            <el-radio :label="1" size="small">基础版本</el-radio>
                            <el-radio :label="2" size="small">增强版本</el-radio>
                        </el-radio-group>
                        <div v-if="storeBaseForm.sync_version === 1" class="formTips">
                            <span class="tips_title">注意：</span>
                            <span v-for="(item, index) in state.baseTips" :key="`k${index}1`">{{ item }}</span>
                        </div>
                        <div v-else class="formTips">
                            <span class="tips_title">注意：</span>
                            <span v-for="(item, index) in state.proTips" :key="`k${index}2`">{{ item }}</span>
                        </div>
                    </el-form-item>

                    <el-form-item v-if="storeBaseForm.sync_type === 1" label="订单数据" label-width="160px">
                        <el-switch v-model="storeBaseForm.order_sync" :active-value="1" :inactive-value="2" />
                        <span class="data_tips">{{
                            storeBaseForm.sync_version === 1 ? state.orderDataTips : state.orderDataTips_2
                        }}</span>
                    </el-form-item>

                    <el-form-item
                        v-if="
                            storeBaseForm.sync_type === 1 &&
                            storeBaseForm.sync_version === 1 &&
                            storeBaseForm.order_sync === 1
                        "
                        label-width="160px"
                        label=""
                        prop="order_sync_cycle">
                        <StepDate v-model="storeBaseForm.order_sync_cycle" />
                    </el-form-item>

                    <el-form-item v-if="storeBaseForm.sync_type === 1" label-width="160px" label="商品数据">
                        <el-switch v-model="storeBaseForm.product_sync" :active-value="1" :inactive-value="2" />
                        <span class="data_tips">{{
                            storeBaseForm.sync_version === 1 ? state.productDataTips : state.productDataTips_2
                        }}</span>
                    </el-form-item>

                    <el-form-item
                        v-if="
                            storeBaseForm.sync_type === 1 &&
                            storeBaseForm.sync_version === 1 &&
                            storeBaseForm.product_sync === 1
                        "
                        label-width="160px"
                        label=""
                        prop="product_sync_cycle">
                        <StepDate v-model="storeBaseForm.product_sync_cycle" end-text="同步新增且更新的商品数据" />
                    </el-form-item>

                    <el-form-item label="解析方式">
                        <el-radio-group v-model="storeBaseForm.decode_way">
                            <el-radio :label="1" size="small">周期解析</el-radio>
                            <el-radio :label="2" size="small">高效解析</el-radio>
                        </el-radio-group>
                        <div class="formTips">
                            <span class="tips_title">注意：</span>
                            <span v-for="item in state.analysisTips" :key="item">{{ item }}</span>
                        </div>
                    </el-form-item>

                    <el-form-item v-if="storeBaseForm.decode_way === 1" label-width="80px" label="" prop="decode_cycle">
                        <StepDate v-model="storeBaseForm.decode_cycle" />
                    </el-form-item>
                </el-form>
            </div>

            <div v-show="step === 2" class="finishBox">
                <el-icon :style="{ fontSize: '60px' }" color="#60B900">
                    <CircleCheckFilled />
                </el-icon>
                <div v-if="type != 'look'">{{ `店铺${!!route.query.shop_id ? '编辑' : '创建'}成功` }}</div>
                <div class="tag">您的客易达店铺ID为：{{ shop_id }} <span @click="copy(shop_id)">复制</span></div>
                <div v-if="open_platform == 1" class="tag">
                    请前往设置与开发去开启开发者功能 <span @click="toSetting">去配置</span>
                </div>
                <div v-if="storeBaseForm.sync_type === 1" class="tag">
                    <el-button type="primary" size="small" @click="contactService">联系客服开通</el-button>
                </div>
            </div>
        </div>
    </el-card>
    <div class="footer_button">
        <el-button v-if="step === 1" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="step === 2" type="primary" @click="done">完成</el-button>
    </div>

    <el-dialog v-model="changePackage" title="企业专属顾问" width="25%" center>
        <div class="qwQrCode" style="text-align: center">
            <img src="https://static.scrm.keyid.cn/assets/images/global/service.png" alt="" />
        </div>
        <p style="text-align: center">扫码添加企微顾问，开通使用！</p>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { addStore, getStoreDetail, editStore } from '@/api/ecommerce/storeManage';
import { commonLinkList } from '@/api/channel/authconfig';
import storeProgress from '../components/storeProgress.vue';
import storeTips from '../components/storeTips.vue';
import StepDate from '../components/StepDate.vue';
import lodash from 'lodash';
import useClipboard from 'vue-clipboard3';
import type { FormInstance, FormRules } from 'element-plus';

const route = useRoute();
const router = useRouter();
const { toClipboard } = useClipboard();

const storeBaseFormRef = ref<FormInstance>();
const step = ref<number>(1); // 步骤数
const shop_id = ref<string | number>('');
const open_platform = ref<string | number>('');
const disabled = ref<boolean>(true);
const clickList = reactive<Array<string>>([]);
const changePackage = ref(false);
const sync_lines = reactive<any>([]);
const query = reactive<any>({
    source: '',
    shop_id: ''
});

// 页面类型：新增、编辑、查看
const { type } = route.query;

const state = reactive<any>({
    baseTips: [
        '1、周期同步抖店订单数据至客易达，同时支持手动同步的入口来获取指定时间段的订单数据。',
        '2、配置了数据同步周期，使得订单、商品数据同步变得自动化可配置，不会影响手动同步订单、商品数据的功能。'
    ],
    proTips: ['实时接收抖店订单数据至客易达，同时支持手动同步的入口来获取指定时间段的订单数据。'],
    orderDataTips: '开启后，即可配置周期同步订单。',
    orderDataTips_2: '开启后，即可实时接收订单变更数据。因平台限制，可能会有一定概率延迟。',
    productDataTips: '开启后，即可配置周期同步商品。',
    productDataTips_2: '开启后，即可实时接收商品变更数据。因平台限制，可能会有一定概率延迟。',
    analysisTips: [
        '1、根据平台限制，每日解析额度存在上限，解析额度不得累加。',
        '2、每日解析额度达到上限之后或者当日已结束，将停止解析。',
        '3、周期解析时，优先解析当日满足解析条件的订单，如果还有额度，才会解析历史未解析订单（按照下单时间倒序解析）。',
        '4、高效解析时，订单状态满足解析条件时，立即解析未解析订单。'
    ]
});

interface StepDateType {
    exec_cycle?: number;
    exec_cycle_type?: string;
    exec_time?: string;
}

type storeBaseFormType = {
    name: string;
    external_shop_id: string;
    data_support: number; // 待定
    sync_type: number;
    order_sync: number;
    product_sync: number;
    sync_version: number;
    decode_way: number;
    order_sync_cycle: StepDateType;
    product_sync_cycle: StepDateType;
    decode_cycle: StepDateType;
    retail_shop_id: string;
};
const storeBaseForm = reactive<storeBaseFormType>({
    name: '',
    external_shop_id: '',
    data_support: 1, // 待定
    sync_type: 1,
    order_sync: 1,
    product_sync: 2,
    sync_version: 1,
    decode_way: 1,
    order_sync_cycle: {
        exec_cycle: 1,
        exec_cycle_type: 'day',
        exec_time: '08:00'
    },
    product_sync_cycle: {
        exec_cycle: 30,
        exec_cycle_type: 'day',
        exec_time: '23:00'
    },
    decode_cycle: {
        exec_cycle: 1,
        exec_cycle_type: 'day',
        exec_time: '08:00'
    },
    retail_shop_id: ''
});

const checkDate = (rule: any, value: any, callback: any) => {
    if (value.exec_cycle_type == 'hour') {
        callback();
    } else if (value.exec_cycle_type == 'day') {
        if (value.exec_time) {
            callback();
        } else {
            callback(new Error('请选择每天提醒的时间点'));
        }
    } else {
        callback(new Error('请选择提醒时间类型'));
    }
};

const storeBaseFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入店铺名称', trigger: 'change' }],
    retail_shop_id: [{ required: true, message: '', trigger: 'change' }],
    external_shop_id: [{ required: true, message: '请输入抖店ID', trigger: 'change' }],
    order_sync_cycle: [{ validator: checkDate, trigger: 'change' }],
    product_sync_cycle: [{ validator: checkDate, trigger: 'change' }],
    decode_cycle: [{ validator: checkDate, trigger: 'change' }]
});

const nextStep = async (): Promise<void> => {
    // 查看店铺下一步时不调用接口
    if (type == 'look') {
        step.value++;
        return;
    }
    if (!storeBaseFormRef.value) return;
    await storeBaseFormRef.value.validate(async (valid: any): Promise<void> => {
        if (valid) {
            let flag = false;
            if (route.query.shop_id) {
                flag = await editStoreCom();
            } else {
                flag = await addStoreCom();
            }
            if (flag) {
                step.value++;
            }
        }
    });
};

const preStep = () => {
    if (step.value > 1) step.value--;
};

const done = () => {
    const path = '/ecommerce/storeManage/list';
    router.push(path);
};

const toCheck = async (urlIdType: string, flag?: boolean) => {
    if (flag) {
        clickList.push(urlIdType);
    }
    const codes = [urlIdType];
    const res = await commonLinkList({ codes });
    const outLink = res[urlIdType].url;
    if (outLink) {
        window.open(outLink, '_blank');
    }
};

const contactService = () => {
    changePackage.value = true;
};

const addStoreCom = async (): Promise<boolean> => {
    let params = lodash.cloneDeep(storeBaseForm);
    const extr = {
        source: query.source
    };
    params = Object.assign({}, params, extr);
    const { shop_id: shop_id_, open_platform: open_platform_ } = await addStore(params);
    if (shop_id_) {
        shop_id.value = shop_id_?.toString();
        open_platform.value = open_platform_;
        return true;
    } else {
        return false;
    }
};

const editStoreCom = async (): Promise<boolean> => {
    let params = lodash.cloneDeep(storeBaseForm);
    const extr = {
        source: query.source,
        shop_id: query.shop_id
    };
    params = Object.assign({}, params, extr);
    shop_id.value = storeBaseForm.retail_shop_id;
    return (await editStore(params)) as boolean;
};

const copy = async (val: string | number) => {
    try {
        await toClipboard(val.toString());
        ElMessage.success('复制成功');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};
const toSetting = () => {
    const path = '/channelconfig/developConfiguration/basicConfiguration';
    router.push(path);
};

const toAgreement = () => {
    const path = '/agreement?show=privacyAgreement';
    window.open(path, '_blank');
};

const height = computed(() => {
    const clientHeight = document.documentElement.clientHeight;
    return `${clientHeight - 380}px`;
});

const getDetailInfo = async (query_shop_id: string) => {
    const {
        name: name = '',
        sync_type: sync_type = 1,
        external_shop_id: external_shop_id = '',
        retail_shop_config: {
            order_sync: order_sync = 1,
            product_sync: product_sync = 2,
            sync_version: sync_version = 1,
            decode_way: decode_way = 1,
            order_sync_cycle: order_sync_cycle = null,
            product_sync_cycle: product_sync_cycle = null,
            decode_cycle: decode_cycle = null
        },
        retail_shop_id: retail_shop_id = ''
    } = await getStoreDetail({ retail_shop_id: query_shop_id });
    storeBaseForm.name = name;
    storeBaseForm.external_shop_id = external_shop_id;
    storeBaseForm.sync_type = sync_type;
    storeBaseForm.order_sync = order_sync;
    storeBaseForm.product_sync = product_sync;
    storeBaseForm.sync_version = sync_version;
    storeBaseForm.decode_way = decode_way;
    storeBaseForm.retail_shop_id = retail_shop_id;
    shop_id.value = retail_shop_id;
    order_sync_cycle && (storeBaseForm.order_sync_cycle = order_sync_cycle);
    product_sync_cycle && (storeBaseForm.product_sync_cycle = product_sync_cycle);
    decode_cycle && (storeBaseForm.decode_cycle = decode_cycle);
};

const init = async () => {
    query.source = Number(route.query.source);
    query.shop_id = route.query.shop_id;
    if (route.query?.shop_id) {
        const shop_id = route.query.shop_id;
        await getDetailInfo(shop_id as string);
    }
};

const handleSync = (val: any) => {
    if (val == 2) {
        storeBaseForm.product_sync = 1;
        storeBaseForm.decode_way = 2;
    } else {
        storeBaseForm.product_sync = 2;
        storeBaseForm.decode_way = 1;
    }
};

onMounted(async () => {
    await init();
});
</script>
<style scoped lang="scss">
.footer_button {
    text-align: center;
    background-color: #fff;
    padding: 16px 24px;
    margin: 0 -16px -16px;
    border-top: 1px solid #eaeaea;
}

.content {
    display: flex;
    justify-content: space-between;
    height: calc(100vh - 339px);

    .withTips {
        display: flex;
        align-items: center;

        span {
            white-space: nowrap;
            text-indent: 12px;
            font-size: 12px;
            color: #ff6b00;

            &:hover {
                color: #f99547;
                cursor: pointer;
            }
        }
    }

    .formTips {
        line-height: 1.6;
        font-size: 12px;
        color: #888;
        background-color: #fffaf9;
        padding: 8px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;

        .toAgreement {
            color: #ff6b00;

            &:hover {
                cursor: pointer;
                color: #f99547;
            }
        }

        .tips_title {
            font-size: 14px;
            color: #ff6b00;
            font-weight: 600;
            margin-bottom: 2px;
        }
    }

    .data_tips {
        padding-left: 8px;
        font-size: 12px;
        color: #666;
    }

    .syncTime {
        display: flex;
        align-items: center;

        span {
            // font-size: 13px;
            color: #777;
            white-space: nowrap;
        }

        .margin-l {
            margin-right: 6px;
        }

        .margin-r {
            margin-left: 6px;
        }

        :deep .el-input {
            width: 160px;
        }
    }

    .storeTips {
        flex: 1;
    }

    .line {
        width: 0;
        border-left: 1px dashed #eee;
        margin: 0 20px 0 8px;
    }

    .msg {
        flex: 1;
        height: v-bind(height);
        overflow: auto;
        padding-left: 10px;
        box-sizing: border-box;
        padding-right: 36px;

        .title {
            border-left: 3px solid #ff6b00;
            padding-left: 8px;
            margin: 10px 0 24px;
        }

        .auth-step {
            margin-bottom: 20px;

            .step-header {
                display: flex;
                justify-content: space-between;
                align-items: center;

                span {
                    font-size: 13px;
                    font-weight: 500;
                    color: #555;
                }
            }

            .step-tips {
                display: flex;
                align-items: center;
                margin: 12px 0;
                padding-left: 16px;

                .tips-dot {
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                    background-color: #ff6b00;
                }

                .tips-text {
                    text-indent: 6px;
                    font-size: 13px;
                    font-weight: 300;
                    color: #555;
                    line-height: 1.5;
                }
            }

            .step-img {
                width: 100%;
                background-color: #fcfcfc;

                img {
                    width: 100%;
                }
            }
        }
    }

    .scroll {
    }

    .finishBox {
        flex: 1;
        height: 500px;
        padding-left: 30px;
        padding-bottom: 100px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        & > div {
            line-height: 1;
            font-size: 13px;
            color: #555;
            margin-top: 16px;
        }

        .tag {
            span {
                color: #ff6b00;

                &:hover {
                    cursor: pointer;
                }
            }
        }
    }
}

.next {
    display: flex;
    justify-content: flex-end;
}

.finished {
    display: flex;
    justify-content: flex-end;
}
</style>
